﻿namespace Digitalmes.Application.Sys.Orgs.Queries;

/// <summary>
/// 按树结构查询组织机构命令。
/// </summary>
/// <param name="OrgId">机构 Id，默认为 0</param>
public record GetOrgListWithTreeQuery(long OrgId = 0) : IRequest<IResult<List<SysOrgDto>>>;

internal sealed class GetOrgListWithTreeQueryHandler(IRepository<SysOrg> repo) : IRequestHandler<GetOrgListWithTreeQuery, IResult<List<SysOrgDto>>>
{
    public async Task<IResult<List<SysOrgDto>>> Handle(GetOrgListWithTreeQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .ToTreeAsync(m => m.Children, m => m.ParentId, request.OrgId, m => m.Id);
        return Result.From(items.Adapt<List<SysOrgDto>>());
    }
}
